<?php

/**
 * Biller Class
 *
 */
class Biller extends CI_Model {

    var $id = 0;
    var $name = '';
    var $amount = 0;
    var $rrule = '';

    /**
     * Constructor
     * 
     */
    function __construct() {

        parent::__construct();

        // Load Utilities
        $this->load->library('utils');
    }

    /**
     * Insert function to create a new biller
     */
    function insert() {

        $data = array(
            'name' => $this->name,
            'amount' => $this->amount,
            'rrule' => $this->rrule
        );

        return $this->db->insert('billers', $data);
    }

    /**
     * Update function to modify an existing biller
     */
    function update() {

        $data = array(
            'name' => $this->name,
            'amount' => $this->amount,
            'rrule' => $this->rrule
        );

        $this->db->where('id', $this->id);
        return $this->db->update('billers', $data);
    }

    /**
     * Delete function to remove an existing biller
     */
    function delete() {
        return $this->db->delete('billers', array('id' => $this->id));
    }

    /**
     * Get function loads a biller from DB
     */
    function get($id) {

        $query = $this->db->get_where('billers', array('id' => $id));

        if ($query->num_rows() == 1) {


            foreach ($query->result() as $row) {
                $this->id = $row->id;
                $this->name = $row->name;
                $this->amount = $row->amount;
                $this->rrule = $row->rrule;
            }

            return true;
        } else {

            return false;
        }
    }

    /**
     * get_bills function to get a list of all bills in chronological order
     */
    function get_bills() {

        // Create Dates
        $start = new DateTime();
        $end = clone $start;
        $end->modify("+12 months");

        // Create an array to hold the bills
        $list = array();

        // Get all the Billers
        $query = $this->db->get('billers');

        // Loop thru each biller
        foreach ($query->result() as $biller) {
            // For each biller, expand its bills
            $this->utils->expand_bills($list, $start, $end, $biller->id, $biller->name, $biller->amount, $biller->rrule);
        }

        // sort bills by date
        $this->utils->sort_bills($list);

        // Return the list of bills
        return $list;
    }

// get_bills()
}

/* End biller.php */
